package com.hot12345.springmvc;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hot12345.common.spring.SpringAbstractController;
import com.hot12345.common.util.MD5;
import com.hot12345.common.util.StringUtil;
import com.hot12345.dao.UserDaoImpl;
import com.hot12345.entity.User;
import com.hot12345.service.CookieService;

@Controller
@RequestMapping("/admin/login")
public class LoginController extends SpringAbstractController {
	
	private final static Log log = LogFactory.getLog(LoginController.class);

	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		String flag = request.getParameter("flag");
		if(flag!=null){
			try{
				modelMap.put("flag", Integer.valueOf(flag));
			}catch(Exception e){
				log.error("Exception", e);
			}
		}
		
		modelMap.put("userName", request.getParameter("userName"));
		modelMap.put("forwardURL", request.getParameter("forwardURL"));
		return new ModelAndView("admin/login");
	}
	
	@RequestMapping("")
	public void login(HttpServletRequest request,
			HttpServletResponse response, 
			ModelMap modelMap,
			@RequestParam("userName") String name,
			@RequestParam("password") String password,
			@RequestParam(value="forwardURL", required=false) String forwardURL) throws Exception {
		
	
		UserDaoImpl userDao = UserDaoImpl.getInstance();
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("name", name);
		params.put("state", 1);
		User user = null;
		try{
			user = userDao.findUniqueByParams(params);
		}catch(Exception e){
			log.error("查询登录用户异常", e);
		}
		
		if(user==null){
			response.sendRedirect("/admin/login/index?flag=-1&userName="+URLEncoder.encode(name, "UTF-8"));return;//用户不存在
		}
		
		String encPassword = MD5.encrypt(password);
		if(encPassword==null || !encPassword.equalsIgnoreCase(user.getPassword())){
			response.sendRedirect("/admin/login/index?flag=-2&userName="+URLEncoder.encode(name, "UTF-8"));return;//密码不正确
		}
		
		
		
		CookieService.addCookie(response, "userID", user.getId().toString());
		CookieService.addCookie(response, "userName", user.getName());
		User loginUser = new User();
		loginUser.setId(user.getId());
		loginUser.setName(user.getName());
		request.getSession().setAttribute("user", loginUser);
		
		if(forwardURL==null || "".equals(forwardURL.trim())){
//			Writer writer = response.getWriter();
//			writer.write("<script>window.location.href=\"/admin/index\";</script>");
			response.sendRedirect("/admin/index");return; //跳转后台默认页
		}
		
		boolean flag = StringUtil.checkDomain(forwardURL);
		if(!flag){
			log.error("非法域名跳转,domain="+forwardURL);
			throw new Exception("非法域名跳转");
		}
//		Writer writer = response.getWriter();
//		writer.write("<script>window.location.href=\""+forwardURL+"\";</script>");
		response.sendRedirect(forwardURL);return; //跳转原来页面
	
	}
	
	/**
	 * 清空Cookie操作 
	 *	
	 * @param request
	 * @param response
	 * @param modelMap
	 * @throws Exception
	 * @author wuzongbao
	 * @date 2013-5-10 上午12:57:05
	 * @version V1.0
	 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,
			HttpServletResponse response, 
			ModelMap modelMap) throws Exception {
		try {
			
				Cookie cookie_userID = new Cookie("userID", "");
				cookie_userID.setPath("/");
				cookie_userID.setMaxAge(-1);
				response.addCookie(cookie_userID);
				
				Cookie cookie_name = new Cookie("userName", "");
				cookie_name.setPath("/");
				cookie_name.setMaxAge(-1);
				response.addCookie(cookie_name);
			
		} catch (Exception ex) {
			log.error("清空Cookies发生异常！",ex);
		}

		// 删除session
		request.getSession().removeAttribute("user"); 
		
		response.sendRedirect("/admin/");
	}
}
